package com.shu.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibFactory {


    public BookServiceImpl getInstance(){
        // 1.创建切面类
        MyAspect myAspect = new MyAspect();

        // 目标增强类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(BookServiceImpl.class);

        enhancer.setCallback(new MethodInterceptor(){
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                myAspect.before();
                Object object = method.invoke(new BookServiceImpl(), args);
                myAspect.after();
                return object;
            }
        });

        return (BookServiceImpl) enhancer.create();
    }
}
